//
//  PKBaseTabBar.swift
//  Panku
//
//  Created by mac on 2017/2/9.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import YYKit

//是否是第一次add
private var isFirstAdd = true

class PKBaseTabBar: PKBaseView {
    
    //MARK: - properties
    //click callback
    var didClickAt:((_ index:Int)->Void)?
    
    var tabBarButtons = [PKBaseButton]()
    
    //MARK: - init
    init(With didClickAt:@escaping ((_ index:Int)->Void)) {
        self.didClickAt = didClickAt
        
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //setupView
    override func setupView() {
        self.backgroundColor = UIColor.white
    }
    
    func addTab(With image:UIImage,selectedImage:UIImage) -> Void{
        
        let button = PKBaseButton.createButton()
        button.tag = self.tabBarButtons.count
        button.addBlock(for: .touchUpInside) { (button) in
            
            //如果是publish按钮则 则不切换selected状态
            if (button as! UIButton).imageView?.image == R.image.tab_publish(){
                self.didClickAt!((button as! PKBaseButton).tag)
                return
            }
            
            //如果是我的界面 外加 没有登录 则不切换selected状态
            if (button as! UIButton).imageView?.image == R.image.tab_mine() &&  PKLoginServices.isLogin() == false{
                self.didClickAt!((button as! PKBaseButton).tag)
                return
            }
            
            //全部按钮unselected
            for button in self.tabBarButtons{
                button.isSelected = false
            }
            
            (button as! PKBaseButton).isSelected = true
            
            self.didClickAt!((button as! PKBaseButton).tag)
        }
        
        button.setImage(image, selectedImage: selectedImage)
        self.tabBarButtons.append(button)
        
        //addSubView
        self.addSubview(button)
        
        //默认选中第一个
        if isFirstAdd == true{

            self.tabBarButtons[0].isSelected = true
            isFirstAdd = false
        }
        
    }
    
    //布局重绘代码
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let tabBarWidth = self.frame.width
        let tabBarHeight = self.frame.height
        
        let tabBarCount = CGFloat(self.tabBarButtons.count)
        
        let tabBarButtonWidth = tabBarWidth/tabBarCount
        let tabBarButtonHeight = tabBarHeight
        
        for(index,button) in self.tabBarButtons.enumerated(){
            
            let frame = CGRect(x: CGFloat(index)*tabBarButtonWidth, y: 0, width: tabBarButtonWidth, height: tabBarButtonHeight)
            button.frame = frame
            
        }
        
    }

}
